import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router'

/**
 * 前置守卫
 */

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/') // 中转到主页,如果next(里有地址)不会执行后置守卫
      nprogress.done()
    } else {
      // 判断是否获取过资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // console.log(roles.menus) // 数组 不确定
        // console.log(asyncRoutes) // 数组 8个
        const filterRoutes = asyncRoutes.filter(item => {
          // return trun/false
          return roles.menus.includes(item.children[0].name)
        }) // 筛选后的路由
        store.commit('user/setRoutes', filterRoutes) // 向store/user里的setRoutes函数提交第二个参数
        // console.log(filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由信息到路由表，404放在最后
        // router添加动态路由之后 需要转发一下
        next(to.path) // 目的是让路由拥有信息 router的缺陷
      } else {
        next() // 放过
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login') // 中转到登录页
      nprogress.done()
    }
  }
})

/**
 * 后置守卫
 */
router.afterEach(() => {
  nprogress.done()
})
